import json
import datetime
from decimal import Decimal


from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.orders.models import OrderInfo, OrderGoods
from apps.users.models import Address, Userwallet, UserWalletLog
from utils.view import LoginRequiredJsonMixin


class OrderSettlementView(LoginRequiredMixin, View):
    """结算订单"""

    def get(self, request):
        """提供订单结算页面"""
        # 获取登录用户
        user = request.user

        # 查询当前用户的所有地址信息
        addresses = Address.objects.filter(user=request.user,
                                               is_deleted=False)

        # 从Redis购物车中查询出被勾选的商品信息
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('carts_%s' % user.id)
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart = {}
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(redis_cart[sku_id])

        # 查询商品信息
        sku_list = []
        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku_list.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'count': cart[sku.id],
                'price':sku.price
            })

        # 补充运费
        # freight = Decimal('10.00')

        addresses_list = []
        for address in addresses:
            addresses_list.append({
                'id':address.id,
                'province':address.province.name,
                'city':address.city.name,
                'district':address.district.name,
                'place':address.place,
                'receiver':address.receiver,
                'mobile':address.mobile
            })

        # 渲染界面
        context = {
            'addresses': addresses_list,
            'skus': sku_list,
            # 'freight': freight,
        }

        return JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'context':context})

class OrderCommitView(LoginRequiredJsonMixin, View):
    """提交订单"""

    def post(self, request):
        """支付
        1.获取用户
        2.获取商品总金额
        3.查询当前用户的账户表
        4.对比价格和账户表的金额，不够返回‘积分不够’
        5.够的话减去账户表信息，并且生成一条交易记录
        """
        """保存订单信息和订单商品信息"""
        # 获取当前要保存的订单数据
        json_dict = json.loads(request.body.decode())
        address_id = json_dict.get('address_id')
        # pay_method = json_dict.get('pay_method')
        # 校验参数
        if not all([address_id]):
            return HttpResponseBadRequest('缺少必传参数')
        # 判断address_id是否合法
        try:
            address = Address.objects.get(id=address_id)
        except Exception:
            return HttpResponseBadRequest('参数address_id错误')

        # 获取登录用户
        user = request.user
        # 生成订单编号：年月日时分秒+用户编号
        order_id =datetime.datetime.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        # 保存订单基本信息 OrderInfo（一）
        order = OrderInfo.objects.create(
            order_id=order_id,
            user=user,
            address=address,
            total_count=0,
            total_amount=Decimal('0'),
            # freight=Decimal('10.00'),
            # pay_method=pay_method,
            status=1
        )
        # 从redis读取购物车中被勾选的商品信息
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('carts_%s' % user.id)
        selected = redis_conn.smembers('selected_%s' % user.id)
        carts = {}
        for sku_id in selected:
            carts[int(sku_id)] = int(redis_cart[sku_id])
        sku_ids = carts.keys()

        # 遍历购物车中被勾选的商品信息
        for sku_id in sku_ids:
            # 查询SKU信息
            sku = SKU.objects.get(id=sku_id)
            # 判断SKU库存
            sku_count = carts[sku.id]
            if sku_count > sku.stock:
                return JsonResponse({'code': 400, 'errmsg': '库存不足'})

            # SKU减少库存，增加销量
            sku.stock -= sku_count
            sku.sales += sku_count
            sku.save()



            # 保存商品订单中总价和总数量
            order.total_count += sku_count
            order.total_amount += (sku_count * sku.price)

        # 添加邮费和保存订单信息

        """账户以及流水"""
        user = request.user
        userwallet = Userwallet.objects.filter(user=user).first()
        if order.total_amount > userwallet.wallet_income:
            return JsonResponse({'code':400,'errmsg':'账户余额不足'})
        else:
            # 保存订单商品信息 OrderGoods（多）
            OrderGoods.objects.create(
                order=order,
                sku=sku,
                count=sku_count,
                price=sku.price,
            )
            order.save()
            wallet_income = (userwallet.wallet_income-order.total_amount)
            # update_wallet = Userwallet(user=user,wallet_income=wallet_income)
            Userwallet.objects.filter(user=user).update(wallet_income=wallet_income)
            number = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            new_wall = UserWalletLog(user=user,number=number,order=order,variation=order.total_amount)
            new_wall.save()
            order.status = 5
            order.save()
            # 清除购物车中已结算的商品
            pl = redis_conn.pipeline()
            pl.hdel('carts_%s' % user.id, *selected)
            pl.srem('selected_%s' % user.id, *selected)
            pl.execute()

            # 响应提交订单结果
            return JsonResponse({'code': 0, 'errmsg': '下单成功', 'order_id': order.order_id})
